package com.zhiyun.yycall.ui;

import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.TextView;

import com.gzit.utils.AndroidUtils;
import com.gzit.utils.StringUtils;
import com.zhiyun.common.YYCallUtils;
import com.zhiyun.message.ChangePwdRequest;
import com.zhiyun.message.ChangePwdResponse;
import com.zhiyun.net.AsynCallback;
import com.zhiyun.net.Net;
import com.zhiyun.net.Response;
import com.zhiyun.trace.TraceActivity;
import com.zhiyun.yycall.Config;
import com.zhiyun.yycall.R;

public class ChangePwdActivity extends TraceActivity {

	private EditText newPasswordView;
	private EditText passwordView;
	private String phoneNo;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.change_pwd_activity);
		newPasswordView = (EditText) this.findViewById(R.id.new_password);
		passwordView = (EditText) this.findViewById(R.id.password);

		phoneNo = Config.getPhoneNo();
		((TextView) this.findViewById(R.id.phoneNo)).setText(phoneNo);

		this.findViewById(R.id.change_pwd_btn).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View v) {

						if (StringUtils.isBlank(passwordView.getText()
								.toString())) {
							AndroidUtils.toastShort("请输入旧密码");
							return;

						}

						if (StringUtils.isBlank(newPasswordView.getText()
								.toString())) {
							AndroidUtils.toastShort("请输入新密码");
							return;

						}

						if (!passwordView.getText().toString().trim()
								.equals(Config.getPlainPassword())) {
							AndroidUtils.toastShort("旧密码不正确，请重新输入");
							return;

						}

						remoteChangePwd();

					}
				});

	}

	private void remoteChangePwd() {

		final String password = passwordView.getText().toString();
		final String newPassword = newPasswordView.getText().toString();

		ChangePwdRequest req = new ChangePwdRequest();
		req.setPhoneNo(phoneNo);
		req.setPassword(YYCallUtils.encryptPwd(phoneNo, password));
		req.setNewPassword(YYCallUtils.encryptPwd(phoneNo, newPassword));

		Net.doHttpRemote(this, req, new ChangePwdResponse(),
				new AsynCallback<Response>() {

					@Override
					public boolean callback(Response r) {
						if (r.isFail()) {
							AndroidUtils.toastLong("修改密码失败，原因:" + r.getError());
							return false;

						}

						// 保存新密码
						Config.setPassword(newPassword);
						AndroidUtils.toastShort("密码修改成功");
						finish();
						return false;
					}
				});

	}
}
